package com.zt.chatgpt.auth.service;

import com.google.common.cache.Cache;
import com.zt.chatgpt.auth.model.entity.AuthStateEntity;
import com.zt.chatgpt.auth.model.valobj.AuthTypeVO;
import com.zt.chatgpt.auth.repository.IAuthRepository;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: zt
 * @Description: 鉴权服务
 * @create: 2024-05-18 23:20
 */
@Slf4j
@Service
public class AuthService extends AbstractAuthService{

    @Resource
    private Cache<String, String> codeCache;

    @Resource
    private IAuthRepository authRepository;

    @Override
    protected AuthStateEntity checkCode(String code) {
        // 1. 验证code（是否过期、不存在）
        String openId = authRepository.getCodeByUserOpenId(code);
        if (StringUtils.isBlank(openId)) {
            log.info("鉴权，用户输入验证码不存在 {}", code);
            return AuthStateEntity.builder()
                    .code(AuthTypeVO.A0001.getCode())
                    .info(AuthTypeVO.A0001.getInfo())
                    .build();
        }

        // 2. 移除code
       authRepository.removeCodeByUserOpenId(openId, code);

        // 3. 验证成功
        return AuthStateEntity.builder()
                .code(AuthTypeVO.A0000.getCode())
                .info(AuthTypeVO.A0000.getInfo())
                .openId(openId)
                .build();
    }

    @Override
    public boolean checkToken(String token) {
        return super.isVerify(token);
    }

    @Override
    public String openid(String token) {
        Claims claim = super.decode(token);
        return claim.get("openId").toString();
    }
}
